// 现代化大屏监控系统JavaScript
class ModernDashboard {
    constructor() {
        this.currentWorkshop = '经编1';
        this.refreshInterval = 30000; // 30秒刷新一次
        this.timer = null;
        this.apiBaseUrl = '/api/dashboard';
        this.isLoading = false;
        this.notifications = [];
        
        this.init();
    }

    // 初始化
    init() {
        this.updateTime();
        this.bindEvents();
        this.loadData();
        this.startAutoRefresh();
        this.updateChart();
    }

    // 绑定事件
    bindEvents() {
        // 页面可见性变化时重新加载数据
        document.addEventListener('visibilitychange', () => {
            if (!document.hidden) {
                this.loadData();
            }
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'r') {
                e.preventDefault();
                this.refreshData();
            }
        });

        // 窗口大小变化时调整布局
        window.addEventListener('resize', this.debounce(() => {
            this.updateChart();
        }, 300));
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 更新当前时间
    updateTime() {
        const now = new Date();
        const dateStr = now.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            weekday: 'long'
        });
        const timeStr = now.toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });

        document.getElementById('current-date').textContent = dateStr;
        document.getElementById('current-time').textContent = timeStr;

        // 每秒更新时间
        setTimeout(() => this.updateTime(), 1000);
    }

    // 加载所有数据
    async loadData() {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.showLoading('machine-loading');
        this.showLoading('custom-machine-loading');

        try {
            // 并行加载数据和系统状态
            const [dataResponse, statusResponse] = await Promise.all([
                fetch(`${this.apiBaseUrl}/all-data?workshopType=${this.currentWorkshop}`),
                fetch(`${this.apiBaseUrl}/system-status`)
            ]);

            const dataResult = await dataResponse.json();
            const statusResult = await statusResponse.json();

            if (dataResult.code === 200) {
                this.updateMachineTable(dataResult.data.machineInfo);
                this.updateCustomMachineTable(dataResult.data.customMachineInfo);
                this.updateStatistics(dataResult.data);
                this.updateLastUpdateTime();
            } else {
                throw new Error(dataResult.message || '数据加载失败');
            }

            // 更新系统状态
            if (statusResult.code === 200) {
                this.updateSystemStatus(statusResult.data);
            }

        } catch (error) {
            console.error('数据加载失败:', error);
            this.showNotification('数据加载失败: ' + error.message, 'error');
        } finally {
            this.hideLoading('machine-loading');
            this.hideLoading('custom-machine-loading');
            this.isLoading = false;
        }
    }

    // 更新机台信息表格
    updateMachineTable(machineInfoList) {
        const tbody = document.getElementById('machine-table-body');
        const countElement = document.getElementById('machine-count');
        
        tbody.innerHTML = '';
        countElement.textContent = machineInfoList ? machineInfoList.length : 0;

        if (!machineInfoList || machineInfoList.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align: center; color: rgba(255, 255, 255, 0.6); padding: 2rem;">
                        <i class="fas fa-inbox" style="font-size: 2rem; margin-bottom: 1rem; display: block;"></i>
                        暂无数据
                    </td>
                </tr>
            `;
            return;
        }

        machineInfoList.forEach((machine, index) => {
            const row = document.createElement('tr');
            
            // 根据剩余时间设置行样式和状态
            const remainingTime = parseFloat(machine.remainingTime) || 0;
            let statusClass = 'status-row-normal';
            let statusIcon = '<i class="fas fa-check-circle" style="color: #10b981;"></i>';
            
            if (remainingTime <= 1) {
                statusClass = 'status-row-critical';
                statusIcon = '<i class="fas fa-exclamation-circle" style="color: #ef4444;"></i>';
            } else if (remainingTime <= 3) {
                statusClass = 'status-row-warning';
                statusIcon = '<i class="fas fa-exclamation-triangle" style="color: #f59e0b;"></i>';
            }

            row.className = `${statusClass} fade-in`;
            row.style.animationDelay = `${index * 0.1}s`;

            row.innerHTML = `
                <td>
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                        <span style="font-size: 1rem;">${statusIcon}</span>
                        <span style="font-size: 0.875rem;">${machine.machineNo || '-'}</span>
                    </div>
                </td>
                <td>
                    <span class="badge" style="background: rgba(99, 102, 241, 0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.875rem;">
                        ${machine.warpBeamNo || '-'}
                    </span>
                </td>
                <td>${machine.materialName || '-'}</td>
                <td>
                    <span style="color: ${remainingTime <= 1 ? '#ef4444' : remainingTime <= 3 ? '#f59e0b' : '#10b981'}; font-weight: 600; font-size: 0.875rem;">
                        ${machine.remainingTime || '0.0'}h
                    </span>
                </td>
                <td>${machine.shaftChangeTime || '-'}</td>
                <td>${machine.nextWarpingHeads || '-'}</td>
            `;
            
            tbody.appendChild(row);
        });
    }

    // 更新自定义机台信息表格
    updateCustomMachineTable(customMachineInfoList) {
        const tbody = document.getElementById('custom-machine-table-body');
        const countElement = document.getElementById('custom-machine-count');
        
        tbody.innerHTML = '';
        countElement.textContent = customMachineInfoList ? customMachineInfoList.length : 0;

        if (!customMachineInfoList || customMachineInfoList.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="6" style="text-align: center; color: rgba(255, 255, 255, 0.6); padding: 2rem;">
                        <i class="fas fa-star" style="font-size: 2rem; margin-bottom: 1rem; display: block;"></i>
                        暂无自定义数据
                    </td>
                </tr>
            `;
            return;
        }

        customMachineInfoList.forEach((machine, index) => {
            const row = document.createElement('tr');
            
            // 根据剩余时间设置行样式和状态
            const remainingTime = parseFloat(machine.remainingTime) || 0;
            let statusClass = 'status-row-normal';
            let statusIcon = '<i class="fas fa-check-circle" style="color: #10b981;"></i>';
            
            if (remainingTime <= 1) {
                statusClass = 'status-row-critical';
                statusIcon = '<i class="fas fa-exclamation-circle" style="color: #ef4444;"></i>';
            } else if (remainingTime <= 3) {
                statusClass = 'status-row-warning';
                statusIcon = '<i class="fas fa-exclamation-triangle" style="color: #f59e0b;"></i>';
            }

            row.className = `${statusClass} fade-in`;
            row.style.animationDelay = `${index * 0.1}s`;

            row.innerHTML = `
                <td>
                    <div style="display: flex; align-items: center; gap: 0.5rem;">
                        <span style="font-size: 1rem;">${statusIcon}</span>
                        <span style="font-size: 0.875rem;">${machine.machineNo || '-'}</span>
                    </div>
                </td>
                <td>
                    <span class="badge" style="background: rgba(245, 158, 11, 0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 0.375rem; font-size: 0.875rem;">
                        ${machine.warpBeamNo || '-'}
                    </span>
                </td>
                <td>${machine.materialName || '-'}</td>
                <td>
                    <span style="color: ${remainingTime <= 1 ? '#ef4444' : remainingTime <= 3 ? '#f59e0b' : '#10b981'}; font-weight: 600; font-size: 0.875rem;">
                        ${machine.remainingTime || '0.0'}h
                    </span>
                </td>
                <td>${machine.shaftChangeTime || '-'}</td>
                <td>${machine.nextWarpingHeads || '-'}</td>
            `;
            
            tbody.appendChild(row);
        });
    }

    // 更新统计信息
    updateStatistics(data) {
        const machineInfoList = data.machineInfo || [];
        const customMachineInfoList = data.customMachineInfo || [];
        const allMachines = [...machineInfoList, ...customMachineInfoList];

        // 计算统计数据
        const totalMachines = allMachines.length;
        const warningMachines = allMachines.filter(m => {
            const time = parseFloat(m.remainingTime) || 0;
            return time > 1 && time <= 3;
        }).length;
        const criticalMachines = allMachines.filter(m => {
            const time = parseFloat(m.remainingTime) || 0;
            return time <= 1;
        }).length;

        // 更新UI
        document.getElementById('total-machines').textContent = totalMachines;
        document.getElementById('warning-machines').textContent = warningMachines;
        document.getElementById('critical-machines').textContent = criticalMachines;

        // 更新运行率图表
        const runningRate = totalMachines > 0 ? Math.round(((totalMachines - criticalMachines) / totalMachines) * 100) : 0;
        this.updateChart(runningRate);
    }

    // 更新图表
    updateChart(percentage = 75) {
        const chartCircle = document.querySelector('.chart-circle svg circle:last-child');
        const chartPercentage = document.querySelector('.chart-percentage');
        
        if (chartCircle && chartPercentage) {
            const circumference = 2 * Math.PI * 50; // r = 50
            const offset = circumference - (percentage / 100) * circumference;
            
            chartCircle.style.strokeDashoffset = offset;
            chartPercentage.textContent = `${percentage}%`;
        }
    }

    // 更新系统状态
    updateSystemStatus(statusData) {
        // 更新左侧状态面板
        document.getElementById('total-machines').textContent = statusData.totalMachines || 0;
        document.getElementById('warning-machines').textContent = (statusData.currentAmount || 0) + '米';
        document.getElementById('critical-machines').textContent = (statusData.yesterdayAmount || 0) + '米';

        // 更新运行率图表
        if (statusData.runningRate !== undefined) {
            this.updateChart(statusData.runningRate);
        }

        // 更新系统状态指示器
        const statusDot = document.querySelector('.status-dot');
        const statusText = document.querySelector('.status-indicator span');
        
        if (statusData.status === 'online') {
            statusDot.className = 'status-dot online';
            statusText.textContent = '系统运行中';
        } else {
            statusDot.className = 'status-dot offline';
            statusText.textContent = '系统离线';
        }
    }

    // 显示加载状态
    showLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.style.display = 'flex';
        }
    }

    // 隐藏加载状态
    hideLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.style.display = 'none';
        }
    }

    // 更新最后更新时间
    updateLastUpdateTime() {
        const now = new Date();
        const timeStr = now.toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        document.getElementById('last-update').textContent = timeStr;
    }


    // 显示通知
    showNotification(message, type = 'info', duration = 3000) {
        const container = document.getElementById('notification-container');
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        const iconMap = {
            success: 'fas fa-check-circle',
            error: 'fas fa-times-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };

        notification.innerHTML = `
            <div style="display: flex; align-items: center; gap: 0.75rem;">
                <i class="${iconMap[type]}" style="color: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : type === 'warning' ? '#f59e0b' : '#6366f1'};"></i>
                <span>${message}</span>
            </div>
        `;

        container.appendChild(notification);

        // 自动移除通知
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideIn 0.3s ease reverse';
                setTimeout(() => {
                    notification.parentNode.removeChild(notification);
                }, 300);
            }
        }, duration);
    }

    // 手动刷新数据
    refreshData() {
        const refreshBtn = document.querySelector('.refresh-btn');
        if (refreshBtn) {
            refreshBtn.style.transform = 'rotate(360deg)';
            setTimeout(() => {
                refreshBtn.style.transform = 'rotate(0deg)';
            }, 500);
        }
        this.loadData();
    }


    // 开始自动刷新
    startAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
        }
        
        this.timer = setInterval(() => {
            this.loadData();
        }, this.refreshInterval);
    }

    // 停止自动刷新
    stopAutoRefresh() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    // 销毁实例
    destroy() {
        this.stopAutoRefresh();
    }
}

// 全局函数
function refreshData() {
    if (window.modernDashboard) {
        window.modernDashboard.refreshData();
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.modernDashboard = new ModernDashboard();
});

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
    if (window.modernDashboard) {
        window.modernDashboard.destroy();
    }
});

// 错误处理
window.addEventListener('error', (e) => {
    console.error('页面错误:', e.error);
    if (window.modernDashboard) {
        window.modernDashboard.showNotification('页面发生错误，请刷新页面', 'error');
    }
});

// 网络状态检测
window.addEventListener('online', () => {
    if (window.modernDashboard) {
        window.modernDashboard.showNotification('网络连接已恢复', 'success');
    }
});

window.addEventListener('offline', () => {
    if (window.modernDashboard) {
        window.modernDashboard.showNotification('网络连接已断开', 'warning');
    }
});
